<?php

namespace Plugin\Message\Listener;

use Common\Common;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Plugin\Alarm\Event\AlarmEvent;
use Plugin\Alarm\Repository\RdAlarmTypeRepository;
use Plugin\Message\Service\MessageService;
use Plugin\Organization\Repository\RdOrganizeUserStandRepository;
use Plugin\Organization\Service\RdOrganizeUserStandService;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

#[Listener]
class AlarmListener implements ListenerInterface
{
    public function __construct(
        protected readonly MessageService $messageService
    ) {}
    public function listen(): array
    {
        return [
            AlarmEvent::class
        ];
    }

    public function process(object $event): void
    {
        $standId = $event->standId;
//        获取站点管理员和安全员
        try {
            $users = Common::container()->get(RdOrganizeUserStandRepository::class)
                ->getStandUsers($standId);
        } catch (\Throwable $e) {
            Common::logException(__CLASS__, $e);
            $users = [];
        }
        try {
            $eventType = Common::container()->get(RdAlarmTypeRepository::class)->findById($event->typeId);
        } catch (\Throwable $e) {
            Common::logException(__CLASS__, $e);
        }
        if (!empty($users)) {
            $this->messageService->createAlarmMessage($users,
                '安全预警',
                ($eventType->risk_title ?? '') . '预警事件已触发，请及时处理。',
                relatedId: $event->msgId,
                level: $eventType->risk_level ?? 1
            );
        }
    }

}